package com.vadmin.vadminjava.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/********************************************************************************
 *
 * 过滤器
 *
 * ******************************************************************************/

@Configuration
public class FilterConfig {

	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
		corsConfiguration.addAllowedHeader("*"); // 2允许任何头
		corsConfiguration.addAllowedMethod("*"); // 3允许任何方法（post、get等）
		corsConfiguration.setAllowCredentials(true); // 允许cookies跨域
		return corsConfiguration;
	}

	@Bean
	public FilterRegistrationBean corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig());
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new CorsFilter(source));
		// 设置 Filter 的优先级为最高优先级(如果有多个过滤器这些过滤器会有一个先后顺序的问题)
		filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
		return filterRegistrationBean;
	}

	//下面的注解注释掉就不会生效了
	@Bean
	public FilterRegistrationBean filterRegist() {
		FilterRegistrationBean frBean = new FilterRegistrationBean();
		frBean.setFilter(new MyFilter());

		//frBean.addInitParameter("exclusions", "/AdminServlet/userLogin");//这个狗日的是干嘛的，百度无果

		frBean.addUrlPatterns("/*"); //2个*号是包括子路径？
		//frBean.addUrlPatterns("/AdminServlet/*");
		//frBean.addUrlPatterns("/AdminPermissionServlet/*");
		//frBean.addUrlPatterns("/AdminProjectServlet/*");

		return frBean;
	}

}